{% extends 'form.html' %}

{% block other_buttons %}
    <button id="send_captcha_btn" class="btn btn-primary pull-left">发送验证码</button>
{% endblock %}

{% block script_extends%}
    <script type="text/javascript">
        $("#send_captcha_btn").click(function(event){
            event.preventDefault();
            // 异步发送验证码
            $.ajax({
                url:"{% url 'send_captcha' %}",
                type:'GET',
                data:{
                    email:$("#retrieve_email").val(),
                    cache_prefix:'retrieve_captcha',
                },
                cache:false,
                success:function(data){
                    console.log(data);
                    if(data['status']=='SUCCESS'){
                        $("#tip").text("验证码已发送，请前往邮箱查看");
                    }else{
                        $("#tip").text(data['message']);
                    }
                },
                error:function(xhr){
                    console.log(xhr);
                    alert('发送验证码异常');
                }
            });

            // 设置按钮无法点击
            var interval = 30;
            $(this).attr({"disabled":"disabled"});
            $(this).text(interval+'s');
            // 30s发送间隔
            var timer = setInterval(() => {
                console.log($(this));
                if(interval <= 0){
                    clearInterval(timer);
                    $(this).removeAttr("disabled");
                    $(this).text("发送验证码");
                    return;
                }
                interval--;
                $(this).text(interval+'s');
            }, 1000);
        });
    </script>
{% endblock %}